/*
 * Created by SharpDevelop.
 * User: MyWife
 * Date: 11/30/2009
 * Time: 11:25 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using popLib;
using System.IO;
using System.Diagnostics;

namespace AppStoreManager
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		Profile settings;
		IconForm iconform;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//set action browse folder for textbox
			SetBrowseForTextBox( btn_icon_folder, txt_icon_folder );
			SetBrowseForTextBox( btn_root_folder, txt_root_folder );
			loadConfig();
			
			//set drag action for drag icon to form
			FormLib.dragAndDrop( groupBox1, dragImage );
			FormLib.dragAndDrop( txt_info_icon, dragImage );
			FormLib.dragAndDrop( this, dragImage );
									
			iconform = new IconForm();
		}
		
		void dragImage( Control control, string[] files ){
			if( _currentSelectedPath != null ){
				txt_info_icon.Text = files[0];
				showPreview();
			}
		}
		
		//set action for button -> and save value to textbox
		void SetBrowseForTextBox( Button command, TextBox textbox ){
			command.Click += delegate(object sender, EventArgs e) {
				ReturnSet rs = FormLib.folderBrowser();
				if( rs.Success ) textbox.Text = rs.Result+"";
			};
			textbox.DoubleClick += delegate(object sender, EventArgs e) {
				ReturnSet rs = FormLib.folderBrowser();
				if( rs.Success ) textbox.Text = rs.Result+"";
			};
		}
		
		
		#region application config
		void loadConfig(){
			settings = popLib.ProfileLib.initProfile( ProfileLib.ProfileType.Ini, FileLib.getFullPath("setting.ini") );
			txt_root_folder.Text = settings.getValue( "Settings", "RootFolder", @"D:\My Documents\Applications\#AppStore" );
			txt_icon_folder.Text = settings.getValue( "Settings", "IconFolder", @"D:\My Documents\Applications\#AppStore\@Common\Icons" );
			txt_tag.Text		 = settings.getValue( "Settings", "Tag", "Internet; CD & DVD; Design & Coding; Dictionary; Hardware; Internet; Multimedia; Office & Document; Security; Windows" );
			txt_group.Text		 = settings.getValue( "Settings", "Group", "Internet; CD & DVD; Design & Coding; Dictionary; Hardware; Internet; Multimedia; Office & Document; Security; Windows" );
			cbx_autoicon.Checked = settings.getBoolean( "Settings", "AutoSaveIconFromClipboard", false );
			cbx_autosave.Checked = settings.getBoolean( "Settings", "AutoSaveAppConfig", false );
		}
		
		void saveConfig(){
			settings.setValue( "Settings", "RootFolder", txt_root_folder.Text );
			settings.setValue( "Settings", "IconFolder", txt_icon_folder.Text );
			settings.setValue( "Settings", "Tag", txt_tag.Text );
			settings.setValue( "Settings", "Group", txt_group.Text );
			settings.setBoolean( "Settings", "AutoSaveIconFromClipboard", cbx_autoicon.Checked );
			settings.setBoolean( "Settings", "AutoSaveAppConfig", cbx_autosave.Checked );
		}
		
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			saveConfig();
		}
		#endregion
		
		
		//when click on the tab control 
		void TabControl1TabIndexChanged(object sender, EventArgs e)
		{
			//if click on the second tab [Manage AppStore] --> load all app and it's config
			if( tabControl1.SelectedIndex == 1 ){
				if( !StringLib.isValid(txt_root_folder.Text) || !Directory.Exists(txt_root_folder.Text) ){
					FormLib.alert("Please choose an existed root folder!!!");
					return;
				}
				
				if( !StringLib.isValid(txt_icon_folder.Text) || !Directory.Exists(txt_icon_folder.Text) ){
					FormLib.alert("Please choose an existed icon folder!!!");
					return;
				}
				
				//init tree
				treeView1.Nodes.Clear();
				string[] groupFolders = FileLib.getFileList( txt_root_folder.Text, "#*", false, FileLib.SearchOption.FolderOnly );
				foreach( string folderName in groupFolders ){
					TreeNode currentNode = treeView1.Nodes.Add( Path.GetFileName(folderName).Substring(1) );
					
					string[] appFolders = FileLib.getFileList( folderName, "*", false, FileLib.SearchOption.FolderOnly );
					foreach( string appName in appFolders ){
						if( !appName.Contains("#More") ){
							TreeNode appNode = currentNode.Nodes.Add( Path.GetFileName(appName) );
							loadAppConfig( appNode, appName );
						}
					}
				}
				
				//init tag and group
				string[] tags = StringLib.splitByAny( txt_tag.Text.Replace("; ",";"), ";,|" );
				clb_info_tag.Items.Clear();
				clb_info_tag.Items.AddRange( tags );
				
				string[] groups = StringLib.splitByAny( txt_group.Text.Replace("; ",";"), ";,|" );
				cmb_info_group.Items.Clear();
				cmb_info_group.Items.AddRange( groups );
				
			} else if( tabControl1.SelectedIndex == 2 ){
				
			}
		}
		
		TreeNode _currentSelectdNode = null;
		string _currentSelectedPath = "";
		//click on treee node --> view app detail
		void TreeView1AfterSelect(object sender, TreeViewEventArgs e)
		{
			//check for autosave config
			if( cbx_autosave.Checked && btn_save.Enabled && _currentSelectdNode != e.Node ){
				saveConfig( _currentSelectedPath );
				loadAppConfig( _currentSelectdNode, _currentSelectedPath );
			}
			
			//if app node --> view app detail
			if( e.Node.Parent != null && e.Node.Parent.Parent == null ){								
				_currentSelectdNode = e.Node;
				_currentSelectedPath = Path.Combine( txt_root_folder.Text, "#" + e.Node.FullPath );
				btn_save.Enabled = btn_execute.Enabled = btn_selectIcon.Enabled = true;
				loadAppConfig( _currentSelectdNode, _currentSelectedPath, true );
			
			//if child node --> view parent node (app node) detail
			}else if( e.Node.Parent != null && e.Node.Parent.Parent != null ){
				_currentSelectdNode = e.Node.Parent;
				_currentSelectedPath = Path.Combine( txt_root_folder.Text, "#" + e.Node.Parent.FullPath );
				btn_save.Enabled = btn_execute.Enabled = btn_selectIcon.Enabled = true;
				loadAppConfig( _currentSelectdNode, _currentSelectedPath, true );			
				
			//if group node	--> reset all
			}else{
				_currentSelectdNode = null;
				_currentSelectedPath = null;
				resetView();
			}
		}
		
		//reset groupbox information
		void resetView(){
			cmb_info_exe.Items.Clear();
			txt_info_app.Text = txt_info_desc.Text = txt_info_name.Text = txt_info_icon.Text = "";
			resetCheckListBox( clb_info_tag );
			cmb_info_group.SelectedIndex = -1;				
			btn_save.Enabled = btn_execute.Enabled = btn_selectIcon.Enabled = false;
			lbl_preview.Image = null;
		}
		
		//reset checklistbox
		void resetCheckListBox( CheckedListBox clistbox ){
			for( int i = 0; i < clistbox.Items.Count; i++ )
				clistbox.SetItemChecked( i, false );
		}
		
		//load app config
		void loadAppConfig( TreeNode appNode, string applicationPath ){
			loadAppConfig( appNode, applicationPath, false );
		}
		
		//load app config ( load ini file and view in groupbox )
		void loadAppConfig( TreeNode appNode, string applicationPath, bool viewDetail ){
			string config = Path.Combine( applicationPath, "#INFO.INI" );
			
			// if config file is not existed -> reset groupbox
			if( !File.Exists( config ) ){
				resetView();
				return;
			}
			
			//load config
			Profile appProfile = popLib.ProfileLib.initProfile( ProfileLib.ProfileType.Ini, config );
			
			string exe	 = appProfile.getValue("AppStore Information", "ExecuteFile", "");
			string name  = appProfile.getValue("AppStore Information", "Name", "");
			string icon  = appProfile.getValue("AppStore Information", "Icon", "");
			string desc  = appProfile.getValue("AppStore Information", "Description", "");
			string tag   = appProfile.getValue("AppStore Information", "Tag", "");
			string group = appProfile.getValue("AppStore Information", "Group", "");
			
			//view detail in tree view
			appNode.Nodes.Clear();
			appNode.Nodes.Add( "ExecuteFile: " + exe );
			appNode.Nodes.Add( "Name: " + name );
			appNode.Nodes.Add( "Icon: " + icon );
			appNode.Nodes.Add( "Description: " + desc );
			appNode.Nodes.Add( "Tag: " + tag );
			appNode.Nodes.Add( "Group: " + group );
			
			//if true --> view on groupbox
			if( !viewDetail ) return;
			
			
			txt_info_app.Text = Path.GetFileName( appNode.FullPath );
			
			cmb_info_exe.Items.Clear();
			string[] exeFiles = getExeFile( applicationPath );
			foreach( string exefile in exeFiles ) cmb_info_exe.Items.Add( getExactFileName( exefile, applicationPath ) );
			cmb_info_exe.SelectedIndex = cmb_info_exe.FindStringExact(exe);
			
			txt_info_name.Text = name;
			txt_info_icon.Text = icon;
			txt_info_desc.Text = desc;
			
			showPreview();
			
			resetCheckListBox( clb_info_tag );
			string[] tagItems = StringLib.splitByAny( tag, ";,|" );
			foreach( string item in tagItems ){
				if( clb_info_tag.FindStringExact( item.Trim() ) >= 0 )
					clb_info_tag.SetItemChecked( clb_info_tag.FindStringExact( item.Trim() ), true );
			}
			
			cmb_info_group.SelectedIndex = cmb_info_group.FindStringExact(group);
		}
		
		void showPreview(){
			if( StringLib.isValid(txt_info_icon.Text) && File.Exists(txt_info_icon.Text) ){
				Image img = Image.FromFile(txt_info_icon.Text);
				if( img.Width > lbl_preview.Width || img.Height > lbl_preview.Height )
					lbl_preview.Image = ImageLib.createThumbnailImage( img, lbl_preview.Width, lbl_preview.Height );
				else 
					lbl_preview.Image = img;
				
			}else{
				lbl_preview.Image = null;
			}
			GC.Collect();
		}
		
		
		
		//click on save button -> save node
		void Button4Click(object sender, EventArgs e)
		{
			//save config
			saveConfig( _currentSelectedPath );
			
			//view in label
			lbl_status.Text = txt_info_name.Text + " saved";
			
			//reload config on treeview
			loadAppConfig( _currentSelectdNode, _currentSelectedPath );			
		}
		
		//save config from groupbox to ini
		void saveConfig(string applicationPath){
			string config = Path.Combine( applicationPath, "#INFO.INI" );
			Profile appProfile = popLib.ProfileLib.initProfile( ProfileLib.ProfileType.Ini, config );
			
			appProfile.setValue("AppStore Information", "ExecuteFile", cmb_info_exe.SelectedItem != null ? cmb_info_exe.SelectedItem.ToString() : "" );
			
			appProfile.setValue("AppStore Information", "Name", txt_info_name.Text );
			appProfile.setValue("AppStore Information", "Icon", txt_info_icon.Text);
			appProfile.setValue("AppStore Information", "Description", txt_info_desc.Text);
			
			string tag = "";
			foreach( int index in  clb_info_tag.CheckedIndices )
				tag += clb_info_tag.Items[index].ToString()+"; ";
			if( StringLib.isValid( tag ) ) tag = (tag+";").Replace("; ;", "");			
			appProfile.setValue("AppStore Information", "Tag", tag);		
			appProfile.setValue("AppStore Information", "Group", cmb_info_group.SelectedItem != null ? cmb_info_group.SelectedItem.ToString() : "" );
		}
		
		
		//double click on blank app --> set default config
		void TreeView1DoubleClick(object sender, EventArgs e)
		{
			if( treeView1.SelectedNode == null ) return;
			
			//double click on blank new app --> create default value
			if( treeView1.SelectedNode.Parent != null && treeView1.SelectedNode.Parent.Parent == null && treeView1.SelectedNode.Nodes.Count == 0 ){
				_currentSelectdNode = treeView1.SelectedNode;
				_currentSelectedPath = Path.Combine( txt_root_folder.Text, "#" + treeView1.SelectedNode.FullPath );
				setDefaultConfig( _currentSelectdNode, _currentSelectedPath );
				loadAppConfig( _currentSelectdNode, _currentSelectedPath, true );
				btn_save.Enabled = btn_execute.Enabled = btn_selectIcon.Enabled = true;
			}
		}
		
		//set default config
		void setDefaultConfig( TreeNode appNode, string applicationPath ){
			string config = Path.Combine( applicationPath, "#INFO.INI" );
			Profile appProfile = popLib.ProfileLib.initProfile( ProfileLib.ProfileType.Ini, config );
			
			string[] exeFiles = getExeFile( applicationPath );
			appProfile.setValue("AppStore Information", "ExecuteFile", exeFiles.Length == 1 ? getExactFileName(exeFiles[0], applicationPath) : "" );
			appProfile.setValue("AppStore Information", "Name", Path.GetFileName(appNode.FullPath) );
			appProfile.setValue("AppStore Information", "Icon", "" );
			appProfile.setValue("AppStore Information", "Description", "" );
			appProfile.setValue("AppStore Information", "Tag", "");
			appProfile.setValue("AppStore Information", "Group", "" );
		}
		
		//get relative filename of execute file
		//if exe in current folder -> get filename only ex: app.exe
		//if exe in sub folder -> add subfolder to filename. ex: bin\app.exe
		string getExactFileName( string exeFile, string applicationPath ){
			//if exe in sub folder
			//if( exeFile.Contains("Sharp") ) FormLib.alert( applicationPath.ToLower() +"\r\n" + Path.GetDirectoryName( exeFile ) );
			if( applicationPath.ToLower() != Path.GetDirectoryName( exeFile ).ToLower() ){
				return Path.Combine( Path.GetFileName( Path.GetDirectoryName( exeFile ) ), Path.GetFileName( exeFile ) );				
			}else return Path.GetFileName( exeFile );
		}
		
		//get all exe file in app folder, if no exe in current folder -> get all exe (include sub folder)
		string[] getExeFile(string applicationPath){
			string[] exeFiles = FileLib.getFileList( applicationPath, "*.exe", false, FileLib.SearchOption.FileOnly );
			if( exeFiles.Length == 0 ) exeFiles = FileLib.getFileList( applicationPath, "*.exe", true, FileLib.SearchOption.FileOnly );
			return exeFiles;
		}
		
		
		
		void Button2Click(object sender, EventArgs e)
		{
			ReturnSet rs = FormLib.openFile( "Icon files(*.png;*.jpg;*.bmp)|*.png;*.jpg;*.bmp|All files(*.*)|*.*", txt_icon_folder.Text );
			if( rs.Success ){
				txt_info_icon.Text = rs.Result+"";				
			}
			showPreview();
		}
		
		void Btn_executeClick(object sender, EventArgs e)
		{
			if( cmb_info_exe.SelectedIndex >= 0 ){
				string exeFile = Path.Combine( _currentSelectedPath, cmb_info_exe.SelectedItem.ToString() );
				ProcessStartInfo info = new ProcessStartInfo(exeFile);
				info.WorkingDirectory = Path.GetDirectoryName( exeFile );
				System.Diagnostics.Process.Start(info);
			}
		}
		
		
	}
}
